package com.sinosoft.taxbenefit.core.applicant.biz.service.impl;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.ws.BindingProvider;
import javax.xml.ws.Holder;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.sinosoft.platform.base.TaxBaseService;
import com.sinosoft.platform.common.config.SystemConstants;
import com.sinosoft.platform.common.exception.BusinessDataErrException;
import com.sinosoft.platform.common.util.DateUtil;
import com.sinosoft.platform.common.util.ReflectionUtil;
import com.sinosoft.platform.common.util.StringUtil;
import com.sinosoft.taxbenefit.api.base.EBResultCodeDTO;
import com.sinosoft.taxbenefit.api.base.HXResultCodeDTO;
import com.sinosoft.taxbenefit.api.config.ENUM_BZ_RESPONSE_RESULT;
import com.sinosoft.taxbenefit.api.config.ENUM_DISPOSE_TYPE;
import com.sinosoft.taxbenefit.api.config.ENUM_SENDSERVICE_CODE;
import com.sinosoft.taxbenefit.api.dto.request.TaxFaulTaskDTO;
import com.sinosoft.taxbenefit.api.dto.request.applicant.RepAppAcceptOneBody;
import com.sinosoft.taxbenefit.api.dto.request.applicant.ReqAppAcceptMoreBody;
import com.sinosoft.taxbenefit.api.dto.request.applicant.ReqAppBeneficiaryDTO;
import com.sinosoft.taxbenefit.api.dto.request.applicant.ReqAppCoverageDTO;
import com.sinosoft.taxbenefit.api.dto.request.applicant.ReqAppGroupPolicyHolderDTO;
import com.sinosoft.taxbenefit.api.dto.request.applicant.ReqAppInsuredDTO;
import com.sinosoft.taxbenefit.api.dto.request.applicant.ReqAppLiabilityDTO;
import com.sinosoft.taxbenefit.api.dto.request.applicant.ReqAppPolicyDTO;
import com.sinosoft.taxbenefit.api.dto.request.applicant.ReqAppPremiumDTO;
import com.sinosoft.taxbenefit.api.dto.request.applicant.ReqAppSinglePolicyHolderDTO;
import com.sinosoft.taxbenefit.api.dto.request.applicant.ReqAppUnderwritingDTO;
import com.sinosoft.taxbenefit.api.dto.request.applicant.ReqPolicyCancelDTO;
import com.sinosoft.taxbenefit.api.dto.request.applicant.ReqPolicyReversalDTO;
import com.sinosoft.taxbenefit.api.dto.request.base.CoreRequestHead;
import com.sinosoft.taxbenefit.api.dto.request.base.ParamHeadDTO;
import com.sinosoft.taxbenefit.api.dto.request.base.ThirdSendResponseDTO;
import com.sinosoft.taxbenefit.api.dto.response.applicant.ResultApplicantDTO;
import com.sinosoft.taxbenefit.api.dto.response.applicant.ResultApplicantReversalDTO;
import com.sinosoft.taxbenefit.api.dto.response.applicant.ResultClient;
import com.sinosoft.taxbenefit.core.applicant.biz.service.ApplicantCoreService;
import com.sinosoft.taxbenefit.core.applicant.dto.AppAcceptClientResultDTO;
import com.sinosoft.taxbenefit.core.applicant.dto.AppAcceptPolicyResultDTO;
import com.sinosoft.taxbenefit.core.applicant.dto.AppAcceptResultBody;
import com.sinosoft.taxbenefit.core.applicant.dto.AppBeneficiaryDTO;
import com.sinosoft.taxbenefit.core.applicant.dto.AppCoverageDTO;
import com.sinosoft.taxbenefit.core.applicant.dto.AppGroupPolicyHolderDTO;
import com.sinosoft.taxbenefit.core.applicant.dto.AppInsuredDTO;
import com.sinosoft.taxbenefit.core.applicant.dto.AppLiabilityDTO;
import com.sinosoft.taxbenefit.core.applicant.dto.AppPolicyDTO;
import com.sinosoft.taxbenefit.core.applicant.dto.AppPremiumDTO;
import com.sinosoft.taxbenefit.core.applicant.dto.AppSinglePolicyHolderDTO;
import com.sinosoft.taxbenefit.core.applicant.dto.AppUnderwritingDTO;
import com.sinosoft.taxbenefit.core.applicant.dto.EBBody;
import com.sinosoft.taxbenefit.core.applicant.dto.PolicyReversalDTO;
import com.sinosoft.taxbenefit.core.applicant.dto.PolicyReversalInfoDTO;
import com.sinosoft.taxbenefit.core.applicant.dto.PolicyReversalResultDTO;
import com.sinosoft.taxbenefit.core.common.biz.service.CommonCodeService;
import com.sinosoft.taxbenefit.core.common.config.ENUM_BUSINESS_RESULR;
import com.sinosoft.taxbenefit.core.common.config.ENUM_EBAO_SERVICE_PORT_CODE;
import com.sinosoft.taxbenefit.core.common.config.ENUM_HX_SERVICE_PORT_CODE;
import com.sinosoft.taxbenefit.core.common.config.ENUM_RC_STATE;
import com.sinosoft.taxbenefit.core.common.config.ENUM_RESULT_CODE;
import com.sinosoft.taxbenefit.core.common.config.ENUM_TRACK_TYPE;
import com.sinosoft.taxbenefit.core.common.config.ENUUM_CODE_MAPPING;
import com.sinosoft.taxbenefit.core.common.dto.BookSequenceDTO;
import com.sinosoft.taxbenefit.core.common.dto.EbaoServerPortDTO;
import com.sinosoft.taxbenefit.core.common.dto.ReqBusinessDTO;
import com.sinosoft.taxbenefit.core.common.dto.ReqBusinessDetailDTO;
import com.sinosoft.taxbenefit.core.common.dto.SendLogDTO;
import com.sinosoft.taxbenefit.core.common.dto.ThirdSendDTO;
import com.sinosoft.taxbenefit.core.customer.biz.service.CustomerServiceCore;
import com.sinosoft.taxbenefit.core.ebaowebservice.AsynResultQueryService;
import com.sinosoft.taxbenefit.core.ebaowebservice.AsynResultQueryService_Service;
import com.sinosoft.taxbenefit.core.ebaowebservice.PolicyInforceService;
import com.sinosoft.taxbenefit.core.ebaowebservice.PolicyInforceService_Service;
import com.sinosoft.taxbenefit.core.ebaowebservice.PolicyReversalService;
import com.sinosoft.taxbenefit.core.ebaowebservice.PolicyReversalService_Service;
import com.sinosoft.taxbenefit.core.ebaowebservice.ResponseBody;
import com.sinosoft.taxbenefit.core.ebaowebservice.ResponseHeader;
import com.sinosoft.taxbenefit.core.ebaowebservice.ResponseJSON;
import com.sinosoft.taxbenefit.core.faultTask.biz.service.FaultTaskService;
import com.sinosoft.taxbenefit.core.generated.mapper.TaxContStateTrackMapper;
import com.sinosoft.taxbenefit.core.generated.mapper.TaxCustomerMapper;
import com.sinosoft.taxbenefit.core.generated.mapper.TaxFaultTaskMapper;
import com.sinosoft.taxbenefit.core.generated.model.TaxCont;
import com.sinosoft.taxbenefit.core.generated.model.TaxContApplyPerson;
import com.sinosoft.taxbenefit.core.generated.model.TaxContBenefitor;
import com.sinosoft.taxbenefit.core.generated.model.TaxContGroupApplyPerson;
import com.sinosoft.taxbenefit.core.generated.model.TaxContInsured;
import com.sinosoft.taxbenefit.core.generated.model.TaxContPayment;
import com.sinosoft.taxbenefit.core.generated.model.TaxContPolicyDuty;
import com.sinosoft.taxbenefit.core.generated.model.TaxContPolicyUwinfo;
import com.sinosoft.taxbenefit.core.generated.model.TaxContStateTrack;
import com.sinosoft.taxbenefit.core.generated.model.TaxCustomer;
import com.sinosoft.taxbenefit.core.generated.model.TaxFaultTask;
import com.sinosoft.taxbenefit.core.generated.model.TaxPolicyRisk;
import com.sinosoft.taxbenefit.core.policy.biz.service.PolicyService;
import com.sinosoft.taxbenefit.core.policy.config.ENUM_POLICY_STATE;
import com.sinosoft.taxbenefit.core.securityguard.config.ENUM_POLICY_TYPE;
import com.sinosoft.taxbenefit.core.transCode.biz.service.TransCodeService;

/**
 * 承保上传
 * @author zhang
 */
@Service
public class ApplicantCoreServiceImpl extends TaxBaseService implements ApplicantCoreService {
	@Autowired
	TaxCustomerMapper taxCustomerMapper;
	@Autowired
	FaultTaskService faultTaskService;
	@Autowired
	TaxFaultTaskMapper  taxFaultTaskMapper;//异常任务
	@Autowired
	PolicyService policyService;
	@Autowired
	CommonCodeService commonCodeService;// 公用Service
	@Autowired
	TransCodeService transCodeService;// 转码
	@Autowired
	TaxContStateTrackMapper taxContTrackMapper;// 保单信息轨迹
	@Autowired
	CustomerServiceCore  customerService;
	@Override
	public ThirdSendResponseDTO addApplicant( List<ReqAppPolicyDTO> appAcceptBody, ParamHeadDTO paramHeadDTO) {
		ThirdSendResponseDTO thirdSendResponse = new ThirdSendResponseDTO();// 响应核心的报文内容
		String portCode = paramHeadDTO.getPortCode();
		String port = null;
		try {
			List<ReqBusinessDetailDTO> reqBusinessDetailList = new ArrayList<ReqBusinessDetailDTO>();
			ReqBusinessDTO businessDTO = commonCodeService.initReqBusinessDTO();
			if (portCode.equals(ENUM_HX_SERVICE_PORT_CODE.APPLICANT_ONE.code())) {
				port = ENUM_HX_SERVICE_PORT_CODE.APPLICANT_ONE.desc();
			}else if(portCode.equals(ENUM_HX_SERVICE_PORT_CODE.APPLICANT_MORE.code())) {
				port = ENUM_HX_SERVICE_PORT_CODE.APPLICANT_MORE.desc();
			}
			logger.info(port + "承保上传（核心请求）JSON 体数据内容："+ JSONObject.toJSONString(appAcceptBody));
			// 1 转换为中保信Dto
			List<AppPolicyDTO> appAcceptMoresList = this.createDto(appAcceptBody);
			EBBody EBbody = new EBBody();
			EBbody.setPolicyList(appAcceptMoresList);
			// 2发送中保信，接收响应报文
			ThirdSendDTO thirdSendDTO = commonCodeService.createThirdSend(ENUM_EBAO_SERVICE_PORT_CODE.APPACCEPT_UPLOAD.code(),paramHeadDTO, EBbody);
			logger.info(port + "承保上传（请求中保信）JSON 数据内容："+ JSONObject.toJSONString(thirdSendDTO));
			Holder<ResponseHeader> responseHeaderHolder = new Holder<ResponseHeader>();
			Holder<ResponseBody> responseBodyHolder = new Holder<ResponseBody>();
			EbaoServerPortDTO ebaoServerPort = commonCodeService.queryEBaoServerInfoByPortCode(ENUM_EBAO_SERVICE_PORT_CODE.APPACCEPT_UPLOAD.code());
			String portUrl = ebaoServerPort.getPortUrl();
			URL wsdlLocation = new URL(portUrl);
			PolicyInforceService_Service service = new PolicyInforceService_Service(wsdlLocation);
			PolicyInforceService servicePort = service.getPolicyInforceServicePort();
			BindingProvider bp = (BindingProvider) servicePort;
			bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, portUrl);
			servicePort.inforce(thirdSendDTO.getHead(), thirdSendDTO.getBody(),responseHeaderHolder, responseBodyHolder);
			ResponseHeader responseHeader = responseHeaderHolder.value;
			ResponseBody responseBody = responseBodyHolder.value;
			logger.info(port + "（中保信响应）JSON 数据内容："+ responseBody.getJsonString());
			ResponseJSON responseJSON = new ResponseJSON();
			responseJSON.setResponseBody(responseBody);
			responseJSON.setResponseHeader(responseHeader);
			// 记录日志
			SendLogDTO sendLog = new SendLogDTO();
			sendLog.setSerialNo(paramHeadDTO.getSerialNo());
			sendLog.setPortCode(ENUM_EBAO_SERVICE_PORT_CODE.APPACCEPT_UPLOAD.code());
			sendLog.setRequestContent(JSONObject.toJSONString(thirdSendDTO));
			sendLog.setResponseContent(JSONObject.toJSONString(responseJSON));
			sendLog.setTargetCode(ENUM_SENDSERVICE_CODE.EBAO.code());
			sendLog.setState(ENUM_BZ_RESPONSE_RESULT.SUCCESS.code());
			sendLog.setDescription(ENUM_BZ_RESPONSE_RESULT.SUCCESS.description());
			commonCodeService.addLogSend(sendLog);
			// 3.封装返回核心dto;
			if (ENUM_RESULT_CODE.SUCCESS.code().equals(responseHeader.getResultCode())
					|| ENUM_RESULT_CODE.INPUT_LOCALITY_SUCCESS.code().equals(responseHeader.getResultCode())) {
				thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.SUCCESS.code());
				thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.SUCCESS.description());
				// 解析中保信返回Dto
				AppAcceptResultBody resultlist = JSONObject.parseObject(responseBody.getJsonString(),AppAcceptResultBody.class);
				List<AppAcceptPolicyResultDTO> policyList = resultlist.getPolicyList();
				// 持久化
				this.addNewPolicy(appAcceptBody, policyList);
			}else{
				thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.FAIL.code());
				List list = responseHeader.getResultMessage().getMessage();
				if(list != null && list.size() > 0){
					StringBuffer sbStr = new StringBuffer(); 
					for(String mess : responseHeader.getResultMessage().getMessage()){
						sbStr.append(mess).append("|");
					}
					String message = sbStr.substring(0, sbStr.length()-1).toString();
					thirdSendResponse.setResultDesc(message);
				}else{
					thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.FAIL.description());
				}
			}
			boolean isRegisterFaulTask = false;
			if (!StringUtil.isEmpty(responseBody.getJsonString())) {
				AppAcceptResultBody resultBody = JSONObject.parseObject(responseBody.getJsonString(),AppAcceptResultBody.class);
				if (null != resultBody.getPolicyList()) {
					// 成功记录数
					Integer successNum = 0;
					// 失败记录数
					Integer failNum = 0;
					// 返回多条记录
					List<ResultApplicantDTO> bodylist = new ArrayList<ResultApplicantDTO>();
					// 保单list
					List<AppAcceptPolicyResultDTO> policyList = resultBody.getPolicyList();
					// 循环核心dto
					for (ReqAppPolicyDTO accept : appAcceptBody) {
						// 循环返回结果
						for (AppAcceptPolicyResultDTO r : policyList) {
							// 判断保单号
							if (r.getPolicyNo().equals(accept.getPolicyNo())) {
								List<ResultClient> clientList = new ArrayList<ResultClient>();
								ResultApplicantDTO body = new ResultApplicantDTO();
								body.setBizNo(accept.getBizNo());
								body.setPolicyNo(r.getPolicyNo());
								for (AppAcceptClientResultDTO c : r.getClientList()) {
									ResultClient client = new ResultClient();
									HXResultCodeDTO result = new HXResultCodeDTO();
									client.setTaxCode(c.getTaxCode());
									client.setSequenceNo(c.getSequenceNo());
									result.setResultCode(c.getResult().getResultCode());
									List<String> mes = c.getResult().getResultMessage();
									String message = "";
									if (mes != null) {
										StringBuffer sb = new StringBuffer();
										for (String m : mes) {
											sb.append(m).append("|");
										}
										message = sb.substring(0,sb.length() - 1).toString();
									}
									result.setResultMessage(message);
									// 成功记录计数
									if (ENUM_RESULT_CODE.SUCCESS.code().equals(c.getResult().getResultCode())) {
										successNum += 1;
									} else {
										// 失败记录计数
										failNum += 1;
										ReqBusinessDetailDTO reqBusinessDetailDTO = commonCodeService.initReqBusinessDetailDTO(paramHeadDTO);
										reqBusinessDetailDTO.setResultCode(ENUM_BUSINESS_RESULR.FAIL.code());
										reqBusinessDetailDTO.setResultMessage(message);
										reqBusinessDetailList.add(reqBusinessDetailDTO);
									}
									client.setResult(result);
									clientList.add(client);
								}
								body.setClientList(clientList);
								bodylist.add(body);
							}
						}
					}
					// 返回核心对象
					if (ENUM_HX_SERVICE_PORT_CODE.APPLICANT_ONE.code().equals(portCode)) {
						thirdSendResponse.setResJson(bodylist.get(0));
					} else if (ENUM_HX_SERVICE_PORT_CODE.APPLICANT_MORE.code().equals(portCode)) {
						thirdSendResponse.setResJson(bodylist);
					}
					// 登记请求记录
					businessDTO.setReqSuccessNum(successNum);
					businessDTO.setReqFailNum(failNum);
					isRegisterFaulTask = true;
				} else {
					BookSequenceDTO bookSequence = JSONObject.parseObject(responseBody.getJsonString(),BookSequenceDTO.class);
					TaxFaulTaskDTO taxFaulTask = new TaxFaulTaskDTO();
					taxFaulTask.setSerialNo(paramHeadDTO.getSerialNo());
					taxFaulTask.setServerPortCode(paramHeadDTO.getPortCode());
					taxFaulTask.setServerPortName(paramHeadDTO.getPortName());
					taxFaulTask.setAreaCode(paramHeadDTO.getAreaCode());
					taxFaulTask.setDisposeType(ENUM_DISPOSE_TYPE.APPOINTMENT.code());
					taxFaulTask.setBookSequenceNo(bookSequence.getBookingSequenceNo());
					faultTaskService.addTaxFaultTask(taxFaulTask);
					thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.EXCEPTION.code());
					thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.EXCEPTION.description());
				}
			} else {
				businessDTO.setReqFailNum(responseHeader.getRecordNum());
				for (int i = 0; i < responseHeader.getRecordNum(); i++) {
					ReqBusinessDetailDTO reqBusinessDetailDTO = commonCodeService.initReqBusinessDetailDTO(paramHeadDTO);
					reqBusinessDetailDTO.setResultCode(ENUM_BUSINESS_RESULR.FAIL.code());
					reqBusinessDetailDTO.setResultMessage(thirdSendResponse.getResultDesc());
					reqBusinessDetailList.add(reqBusinessDetailDTO);
				}
			}
			if (isRegisterFaulTask) {
				// 添加失败交易记录
				commonCodeService.addReqBusinessDetail(reqBusinessDetailList);
				// 添加请求交易记录数
				businessDTO.setRequetNum(responseHeader.getRecordNum());
				commonCodeService.addReqBusinessCollate(businessDTO);
			}
		} catch (Exception e) {
			e.printStackTrace();
			thirdSendResponse.setResJson(e.getMessage());
			thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.EXCEPTION.code());
			thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.EXCEPTION.description());
			TaxFaulTaskDTO taxFaultTaskDTO = new TaxFaulTaskDTO();
			taxFaultTaskDTO.setServerPortCode(paramHeadDTO.getPortCode());
			taxFaultTaskDTO.setServerPortName(paramHeadDTO.getPortName());
			taxFaultTaskDTO.setAreaCode(paramHeadDTO.getAreaCode());
			taxFaultTaskDTO.setSerialNo(paramHeadDTO.getSerialNo());
			taxFaultTaskDTO.setDisposeType(ENUM_DISPOSE_TYPE.ERROR.code());
			faultTaskService.addTaxFaultTask(taxFaultTaskDTO);
			logger.error(port + "后置处理失败：" + e.getMessage());
		}
		logger.error(port + "后置处理结束!");
		return thirdSendResponse;
	}

	/**
	 * 持久化
	 * @param appAcceptBody
	 * @param policyList
	 */
	private void addNewPolicy(List<ReqAppPolicyDTO> appAcceptBody, List<AppAcceptPolicyResultDTO> policyList) {
		try {
			// 循环核心DTO
			for (ReqAppPolicyDTO policy : appAcceptBody) {
				// 循环结果
				for (AppAcceptPolicyResultDTO r : policyList) {
					// 判断保单号
					if (policy.getPolicyNo().equals(r.getPolicyNo())) {
						//业务号
						String bizNo=policy.getBizNo();
						// 循环客户，判断code
						for (AppAcceptClientResultDTO client : r.getClientList()) {
							String code = client.getResult().getResultCode();
							if (ENUM_RESULT_CODE.SUCCESS.code().equals(code)) {
								// 获取保单信息集合
								TaxCont taxCont = null;
								taxCont = this.changeTaxCont(policy);
								policyService.addPolicyInfo(taxCont);
								// 添加投保人
								if (policy.getPolicyType().equals(ENUM_POLICY_TYPE.SINGLE_POLICY_HOLDER.code())) {
									//添加投保人到客户信息表		
									ReqAppSinglePolicyHolderDTO single=policy.getSinglePolicyHolder();
									this.addOrUpdateCustomerInfo(single,bizNo);
									// 个单
									TaxContApplyPerson applyPerson = changeTaxContApplyPerson(policy.getSinglePolicyHolder(),taxCont.getSid());
									policyService.addPolicyHolder(applyPerson);
								} else {
									// 团单
									TaxContGroupApplyPerson groupApplyPerson = changeGroupApplyPerson(policy.getGroupPolicyHolder(),taxCont.getSid());
									policyService.addGroupPolicyApply(groupApplyPerson);
								}

								// 循环保单信息下的被保人信息
								for (ReqAppInsuredDTO reqAppInsuredDTO : policy.getInsuredList()) {
									//添加被保人到客户信息表
									this.addOrUpdateInsuredInfo(reqAppInsuredDTO,bizNo);								
									// 转被保人Dto
									TaxContInsured insured = changeContInsured(reqAppInsuredDTO, taxCont.getSid());
									policyService.addPolicyInsured(insured);

									// 缴费信息
									ReqAppPremiumDTO premium = reqAppInsuredDTO.getPremium();
									TaxContPayment payment = changePayment(premium, taxCont.getSid());
									policyService.addpayment(payment);

									// 循环被保人信息下的受益人信息 （否-0不指定受益人）
									if (!"0".equals(reqAppInsuredDTO.getBeneficiaryIndi())) {
										for (ReqAppBeneficiaryDTO reqAppBeneficiaryDTO : reqAppInsuredDTO.getBeneficiaryList()) {
											//添加收益人到客户信息表
											this.addOrUpdateCustomer(reqAppBeneficiaryDTO,bizNo);
											//添加受益人
											TaxContBenefitor beneficiary = changeContBenefitor(reqAppBeneficiaryDTO,taxCont.getSid());
											policyService.addBeneficiary(beneficiary);
										}
									}
									// 循环被保人信息下的险种信息
									for (ReqAppCoverageDTO reqAppCoverageDTO : reqAppInsuredDTO.getCoverageList()) {
										// 险种信息下的责任信息
										TaxPolicyRisk policyRisk = changePolicyRisk(reqAppCoverageDTO,taxCont.getSid());
										policyService.addCoverage(policyRisk);
										// 核保
										TaxContPolicyUwinfo underwriting = changeUwinfo(reqAppCoverageDTO.getUnderwriting(),policyRisk.getSid());
										policyService.addUnderwriting(underwriting);
										// 责任
										for (ReqAppLiabilityDTO reqAppLiabilityDTO : reqAppCoverageDTO.getLiabilityList()) {
											TaxContPolicyDuty liability = changePolicyDuty(reqAppLiabilityDTO,policyRisk.getSid());
											policyService.addLiability(liability);
										}
									}
								}
							}
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("承保持久化失败" + e.getMessage());
		}
	}

	private void addOrUpdateCustomer(ReqAppBeneficiaryDTO reqAppBeneficiaryDTO,String bizNo) {
		TaxCustomer customer=new TaxCustomer();
		customer.setBizNo(bizNo);
		customer.setBirthday(DateUtil.parseDate(reqAppBeneficiaryDTO.getBirthday()));
		customer.setCustomerName(reqAppBeneficiaryDTO.getName());
		customer.setGender(reqAppBeneficiaryDTO.getGender());
		customer.setCardNo(reqAppBeneficiaryDTO.getCertiNo());
		customer.setCardType(reqAppBeneficiaryDTO.getCertiType());
		customer.setNationality(reqAppBeneficiaryDTO.getNationality());
		
		customerService.addOrUpdateCustomer(customer);
	}

	private void addOrUpdateInsuredInfo(ReqAppInsuredDTO reqAppInsuredDTO,String bizNo) {
		// 添加被保人到客户信息表
		TaxCustomer taxCustomer = new TaxCustomer();
		taxCustomer.setBizNo(bizNo);
		taxCustomer.setBirthday(DateUtil.parseDate(reqAppInsuredDTO.getBirthday()));
		taxCustomer.setCardNo(reqAppInsuredDTO.getCertiNo());
		taxCustomer.setNationality(reqAppInsuredDTO.getNationality());
		taxCustomer.setCardType(reqAppInsuredDTO.getCertiType());
		taxCustomer.setCustomerName(reqAppInsuredDTO.getName());
		taxCustomer.setCustomerNo(reqAppInsuredDTO.getCustomerNo());
		taxCustomer.setGender(reqAppInsuredDTO.getGender());
		taxCustomer.setResidencePlace(reqAppInsuredDTO.getResidencePlace());
		taxCustomer.setMobile(reqAppInsuredDTO.getMobileNo());
		taxCustomer.setHealthFlag(reqAppInsuredDTO.getHealthFlag());
		taxCustomer.setSocialCareNo(reqAppInsuredDTO.getSocialcareNo());
		taxCustomer.setProfessionCode(reqAppInsuredDTO.getJobCode());
		taxCustomer.setRcState(ENUM_RC_STATE.EFFECTIVE.getCode());
		taxCustomer.setModifyDate(DateUtil.getCurrentDate());
		taxCustomer.setModifierId(SystemConstants.SYS_OPERATOR);
		customerService.addOrUpdateCustomer(taxCustomer);
	}

	private void addOrUpdateCustomerInfo(ReqAppSinglePolicyHolderDTO single,String bizNo) {
		//添加投保人到客户信息表								
		TaxCustomer singleCustomer =new TaxCustomer();
		singleCustomer.setBizNo(bizNo);
		singleCustomer.setCardNo(single.getCertiNo());	
		singleCustomer.setNationality(single.getNationality());
		singleCustomer.setBirthday(DateUtil.parseDate(single.getBirthday()));
		singleCustomer.setCustomerName(single.getName());
		singleCustomer.setCustomerNo(single.getCustomerNo());
		singleCustomer.setGender(single.getGender());
		singleCustomer.setCardType(single.getCertiType());
		singleCustomer.setTaxPayMark(single.getTaxIndi());
		singleCustomer.setPersonalTaxLevyWay(single.getTaxPayerType());
		singleCustomer.setTaxRegisterNo(single.getOrganCode1());
		singleCustomer.setResidencePlace(single.getResidencePlace());
		singleCustomer.setSocietyCreditCode(single.getOrganCode4());
		singleCustomer.setMobile(single.getMobileNo());
		singleCustomer.setRcState(ENUM_RC_STATE.EFFECTIVE.getCode());
		singleCustomer.setModifyDate(DateUtil.getCurrentDate());
		singleCustomer.setCreateDate(DateUtil.getCurrentDate());
		singleCustomer.setModifierId(SystemConstants.SYS_OPERATOR);
		singleCustomer.setCreatorId(SystemConstants.SYS_OPERATOR);
		customerService.addOrUpdateCustomer(singleCustomer);
	}

	@Override
	public ThirdSendResponseDTO policyReversal(ReqPolicyCancelDTO reqPolicyCancelDTO, ParamHeadDTO paramHeadDTO) {
		ThirdSendResponseDTO thirdSendResponse = new ThirdSendResponseDTO();// 响应核心的报文内容
		List<ReqBusinessDetailDTO> reqBusinessDetailList = new ArrayList<ReqBusinessDetailDTO>();
		try {
			ReqBusinessDTO businessDTO = commonCodeService.initReqBusinessDTO();
			logger.info("承保撤销上传（核心请求）JSON 体数据内容："+ JSONObject.toJSONString(reqPolicyCancelDTO));
			PolicyReversalInfoDTO reversalInfo = this.createReversalInfoDTO(reqPolicyCancelDTO);
			PolicyReversalDTO reversalDTO = new PolicyReversalDTO();
			reversalDTO.setPolicyCancel(reversalInfo);
			String portCode = ENUM_EBAO_SERVICE_PORT_CODE.POLICY_REVERSAL.code();
			// 创建请求中保信DTO对象
			ThirdSendDTO thirdSendDTO = commonCodeService.createThirdSend(portCode, paramHeadDTO, reversalDTO);
			logger.info("承保撤销上传（请求中保信）JSON 数据内容："+ JSONObject.toJSONString(thirdSendDTO));
			Holder<ResponseHeader> responseHeaderHolder = new Holder<ResponseHeader>();
			Holder<ResponseBody> responseBodyHolder = new Holder<ResponseBody>();
			// 2.调用中保信接口服务,获得返回结果 存储调用中保信日志表
			EbaoServerPortDTO ebaoServerPort = commonCodeService
					.queryEBaoServerInfoByPortCode(ENUM_EBAO_SERVICE_PORT_CODE.POLICY_REVERSAL.code());
			String portUrl = ebaoServerPort.getPortUrl();
			URL wsdlLocation = new URL(portUrl);
			PolicyReversalService_Service service = new PolicyReversalService_Service(wsdlLocation);
			PolicyReversalService servicePort = service.getPolicyReversalServicePort();
			BindingProvider bp = (BindingProvider) servicePort;
			bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, portUrl);
			servicePort.reversal(thirdSendDTO.getHead(),thirdSendDTO.getBody(), responseHeaderHolder,responseBodyHolder);
			ResponseHeader responseHeader = responseHeaderHolder.value;
			ResponseBody responseBody = responseBodyHolder.value;
			logger.info("承保撤销上传（中保信响应）JSON 数据内容："+ responseBody.getJsonString());
			// 封装中保信返回报文
			ResponseJSON responseJSON = new ResponseJSON();
			responseJSON.setResponseBody(responseBody);
			responseJSON.setResponseHeader(responseHeader);
			// 封装发送报文日志对象
			SendLogDTO sendLog = new SendLogDTO();
			sendLog.setSerialNo(paramHeadDTO.getSerialNo());
			sendLog.setPortCode(portCode);
			sendLog.setRequestContent(JSONObject.toJSONString(thirdSendDTO));
			sendLog.setResponseContent(JSONObject.toJSONString(responseJSON));
			sendLog.setTargetCode(ENUM_SENDSERVICE_CODE.EBAO.code());
			sendLog.setState(ENUM_BZ_RESPONSE_RESULT.SUCCESS.code());
			sendLog.setDescription(ENUM_BZ_RESPONSE_RESULT.SUCCESS.description());
			commonCodeService.addLogSend(sendLog);
			thirdSendResponse.setResJson(null);
			if (ENUM_RESULT_CODE.SUCCESS.code().equals(responseHeader.getResultCode())
					|| ENUM_RESULT_CODE.INPUT_LOCALITY_SUCCESS.code().equals(responseHeader.getResultCode())) {
				thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.SUCCESS.code());
				thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.SUCCESS.description());
				// 4.存储业务表数据
				// 修改保单状态为终止
				this.updatePolicyState(reversalInfo.getPolicyNo());
			}else{
				thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.FAIL.code());
				List list = responseHeader.getResultMessage().getMessage();
				if(list != null && list.size() > 0){
					StringBuffer sbStr = new StringBuffer(); 
					for(String mess : responseHeader.getResultMessage().getMessage()){
						sbStr.append(mess).append("|");
					}
					String message = sbStr.substring(0, sbStr.length()-1).toString();
					thirdSendResponse.setResultDesc(message);
				}else{
					thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.FAIL.description());
				}
			}
			if (!StringUtil.isEmpty(responseBody.getJsonString())) {
				PolicyReversalResultDTO reversalResultDTO = JSONObject.parseObject(responseBody.getJsonString(),PolicyReversalResultDTO.class);
				EBResultCodeDTO eBResultCode = reversalResultDTO.getPolicy().getResult();
				String message = "";
				ResultApplicantReversalDTO reversDTO = new ResultApplicantReversalDTO();
				HXResultCodeDTO resultDTO = new HXResultCodeDTO();
				if (null != eBResultCode.getResultMessage()) {
					StringBuffer sbStr = new StringBuffer();
					for (String mess : eBResultCode.getResultMessage()) {
						sbStr.append(mess).append("|");
					}
					message = sbStr.substring(0, sbStr.length() - 1).toString();
				}
				resultDTO.setResultMessage(message);
				resultDTO.setResultCode(eBResultCode.getResultCode());
				reversDTO.setResult(resultDTO);
				thirdSendResponse.setResJson(reversDTO);
				if (ENUM_RESULT_CODE.SUCCESS.code().equals(eBResultCode.getResultCode())) {
					businessDTO.setReqSuccessNum(businessDTO.getReqSuccessNum() + 1);
				} else {
					businessDTO.setReqFailNum(businessDTO.getReqFailNum() + 1);
					ReqBusinessDetailDTO reqBusinessDetailDTO = commonCodeService.initReqBusinessDetailDTO(paramHeadDTO);
					reqBusinessDetailDTO.setResultCode(ENUM_BUSINESS_RESULR.FAIL.code());
					reqBusinessDetailDTO.setResultMessage(message);
					reqBusinessDetailList.add(reqBusinessDetailDTO);
				}
			} else {
				businessDTO.setReqFailNum(responseHeader.getRecordNum());
				ReqBusinessDetailDTO reqBusinessDetailDTO = commonCodeService.initReqBusinessDetailDTO(paramHeadDTO);
				reqBusinessDetailDTO.setResultCode(ENUM_BUSINESS_RESULR.FAIL.code());
				reqBusinessDetailDTO.setResultMessage(thirdSendResponse.getResultDesc());
				reqBusinessDetailList.add(reqBusinessDetailDTO);
			}
			// 添加失败交易记录
			commonCodeService.addReqBusinessDetail(reqBusinessDetailList);
			businessDTO.setRequetNum(responseHeader.getRecordNum());
			commonCodeService.addReqBusinessCollate(businessDTO);
		} catch (Exception e) {
			e.printStackTrace();
			thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.EXCEPTION.code());
			thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.EXCEPTION.description());
			TaxFaulTaskDTO taxFaultTaskDTO = new TaxFaulTaskDTO();
			taxFaultTaskDTO.setServerPortCode(paramHeadDTO.getPortCode());
			taxFaultTaskDTO.setServerPortName(paramHeadDTO.getPortName());
			taxFaultTaskDTO.setAreaCode(paramHeadDTO.getAreaCode());
			taxFaultTaskDTO.setSerialNo(paramHeadDTO.getSerialNo());
			taxFaultTaskDTO.setDisposeType(ENUM_DISPOSE_TYPE.ERROR.code());
			faultTaskService.addTaxFaultTask(taxFaultTaskDTO);
			logger.error("承保撤销上传后置处理发生异常!异常信息为" + e.getMessage());
		}
		logger.error("承保撤销上传后置处理结束!");
		return thirdSendResponse;
	}

	/**
	 * 将核心信息DTO转为中保信信息DTO
	 * 
	 * @param reqPolicyCancelDTO
	 * @return
	 */
	private PolicyReversalInfoDTO createReversalInfoDTO(ReqPolicyCancelDTO reqPolicyCancelDTO) {
		PolicyReversalInfoDTO reversalInfoDTO = new PolicyReversalInfoDTO();
		ReflectionUtil.copyProperties(reqPolicyCancelDTO, reversalInfoDTO);
		return reversalInfoDTO;
	}

	/**
	 * 修改保单状态 添加保单信息轨迹表
	 * 
	 * @param policyNo
	 */
	private void updatePolicyState(String policyNo) {
		TaxCont taxCont = policyService.queryPolicyByPolicyNo(policyNo);
		if (taxCont != null) {
			taxCont.setContState(ENUM_POLICY_STATE.STOP.code());
			TaxContStateTrack taxContTrack = new TaxContStateTrack();
			taxContTrack.setContId(taxCont.getSid());
			taxContTrack.setContNo(policyNo);
			taxContTrack.setApplyDate(DateUtil.getCurrentDate());
			taxContTrack.setValidDate(DateUtil.getCurrentDate());
			taxContTrack.setCreateDate(DateUtil.getCurrentDate());
			taxContTrack.setModifyDate(DateUtil.getCurrentDate());
			taxContTrack.setCreatorId(SystemConstants.SYS_OPERATOR);
			taxContTrack.setModifierId(SystemConstants.SYS_OPERATOR);
			taxContTrack.setRcState(ENUM_RC_STATE.EFFECTIVE.getCode());
			taxContTrack.setEventType(ENUM_TRACK_TYPE.APPLICANT.code());
			taxContTrack.setEventDescription("撤销");
			taxContTrackMapper.insert(taxContTrack);
			policyService.modifyPolicy(taxCont);
		}
	}

	/**
	 * 封装险种信息
	 * @param coverageDTO
	 *            核心DTO
	 * @param policyId
	 *            保单id
	 * @return
	 */
	private TaxPolicyRisk changePolicyRisk(ReqAppCoverageDTO coverageDTO,Integer policyId) {
		TaxPolicyRisk risk = new TaxPolicyRisk();
		risk.setContId(policyId);
		risk.setRiskCode(coverageDTO.getComCoverageCode());
		risk.setRiskName(coverageDTO.getComCoverageName());
		risk.setCoveragePackageCode(coverageDTO.getCoveragePackageCode());
		risk.setRiskPrem(coverageDTO.getInitialPremium());
		risk.setRiskFee(coverageDTO.getRiskPremium());
		risk.setAppAge(Short.valueOf(coverageDTO.getAgeOfInception().toString()));
		risk.setValidDate(DateUtil.parseDate(coverageDTO.getCoverageEffectiveDate()));
		risk.setExpiredDate(DateUtil.parseDate(coverageDTO.getCoverageExpirationDate()));
		risk.setMainFlag(coverageDTO.getCoverageType());
		risk.setAnnualAmnt(coverageDTO.getSa());
		risk.setAutoRenewFlag(coverageDTO.getRenewIndi());
		risk.setRcState(ENUM_RC_STATE.EFFECTIVE.getCode());
		risk.setCreateDate(DateUtil.getCurrentDate());
		risk.setCreatorId(SystemConstants.SYS_OPERATOR);
		return risk;
	}

	/***
	 * 封装保单受益人
	 * 
	 * @param beneficiaryDTO
	 *            核心DTO
	 * @return
	 */
	private TaxContBenefitor changeContBenefitor(ReqAppBeneficiaryDTO beneficiaryDTO, Integer policyId) {
		TaxContBenefitor benefitor = new TaxContBenefitor();
		benefitor.setContId(policyId);
		benefitor.setBenefitorType(beneficiaryDTO.getBeneficiaryType());
		benefitor.setName(beneficiaryDTO.getName());
		benefitor.setGender(beneficiaryDTO.getGender());
		benefitor.setNationality(beneficiaryDTO.getNationality());
		benefitor.setCardNo(beneficiaryDTO.getCertiNo());
		benefitor.setCardType(beneficiaryDTO.getCertiType());
		benefitor.setToInsuredRelation(beneficiaryDTO.getBenInsuredRelation());
		benefitor.setPriority(Integer.parseInt(beneficiaryDTO.getPriority().toString()));
		benefitor.setProportion(beneficiaryDTO.getProportion());
		benefitor.setRcState(ENUM_RC_STATE.EFFECTIVE.getCode());
		benefitor.setContId(SystemConstants.SYS_OPERATOR);
		benefitor.setCreateDate(DateUtil.getCurrentDate());
		return benefitor;
	}

	/**
	 * 封装被保险人
	 * 
	 * @param insuredDTO
	 * @param policyId
	 * @return
	 */
	private TaxContInsured changeContInsured(ReqAppInsuredDTO insuredDTO, Integer policyId) {
		TaxContInsured insured = new TaxContInsured();
		insured.setContId(policyId);
		insured.setSequenceNo(insuredDTO.getSequenceNo());
		insured.setCustomerNo(insuredDTO.getCustomerNo());
		insured.setName(insuredDTO.getName());
		insured.setGender(insuredDTO.getGender());
		insured.setBirthday(DateUtil.parseDate(insuredDTO.getBirthday()));
		insured.setCardType(insuredDTO.getCertiType());
		insured.setCardNo(insuredDTO.getCertiNo());
		insured.setNationality(insuredDTO.getNationality());
		insured.setMobile(insuredDTO.getMobileNo());
		insured.setResidencePlace(insuredDTO.getResidencePlace());
		insured.setHealthFlag(insuredDTO.getHealthFlag());
		insured.setSocialCareNo(insuredDTO.getSocialcareNo());
		insured.setProfessionCode(insuredDTO.getJobCode());
		insured.setInsuredType(insuredDTO.getInsuredType());
		insured.setMainInsuredNo(insuredDTO.getMainInsuredNo());
		insured.setToInsuredRelation(insuredDTO.getPhInsuredRelation());
		insured.setRcState(ENUM_RC_STATE.EFFECTIVE.getCode());
		insured.setCreatorId(SystemConstants.SYS_OPERATOR);
		insured.setCreateDate(DateUtil.getCurrentDate());
		return insured;
	}

	/**
	 * 封装团体投保人信息
	 * @param groupDTO 核心dto
	 * @param policyId 保单id
	 * @param sequenceNo 分单号
	 * @return
	 */
	private TaxContGroupApplyPerson changeGroupApplyPerson(ReqAppGroupPolicyHolderDTO groupDTO, Integer policyId) {
		TaxContGroupApplyPerson groupApplyPerson = new TaxContGroupApplyPerson();
		groupApplyPerson.setContId(policyId);
		// groupApplyPerson.setSequenceNo(sequenceNo);
		groupApplyPerson.setCustomerNo(groupDTO.getCompanyNo());
		groupApplyPerson.setName(groupDTO.getCompanyName());
		groupApplyPerson.setInsuranceUnitTaxRegisterNo(groupDTO.getOrganCode1());
		groupApplyPerson.setOrganCode(groupDTO.getOrganCode2());
		groupApplyPerson.setBusinesslicenseCode(groupDTO.getOrganCode3());
		groupApplyPerson.setSocietyCreditCode(groupDTO.getOrganCode4());
		groupApplyPerson.setResidencePlace(groupDTO.getResidencePlace());
		groupApplyPerson.setIndustry(groupDTO.getIndustry());
		groupApplyPerson.setCompanyNature(groupDTO.getCompanyNature());
		groupApplyPerson.setEmployeeNumber(groupDTO.getEmployeeNumber());
		groupApplyPerson.setListIndi(groupDTO.getListedIndi());
		groupApplyPerson.setRcState(ENUM_RC_STATE.EFFECTIVE.getCode());
		groupApplyPerson.setCreatorId(SystemConstants.SYS_OPERATOR);
		groupApplyPerson.setCreateDate(DateUtil.getCurrentDate());

		return groupApplyPerson;
	}

	/**
	 * 封装本系统的个人投保信息
	 * @param singleDTO 核心DTO
	 * @param policyId 保单id
	 * @return
	 */
	private TaxContApplyPerson changeTaxContApplyPerson(ReqAppSinglePolicyHolderDTO singleDTO, Integer policyId) {
		TaxContApplyPerson applyPerson = new TaxContApplyPerson();
		applyPerson.setContId(policyId);
		applyPerson.setCustomerCode(singleDTO.getCustomerNo());
		applyPerson.setName(singleDTO.getName());
		applyPerson.setGender(singleDTO.getGender());
		applyPerson.setBirthday(DateUtil.parseDate(singleDTO.getBirthday()));
		applyPerson.setCardType(singleDTO.getCertiType());
		applyPerson.setCardNo(singleDTO.getCertiNo());
		applyPerson.setNationality(singleDTO.getNationality());
		applyPerson.setTaxIndi(singleDTO.getTaxIndi());
		applyPerson.setTaxPayerType(singleDTO.getTaxPayerType());
		applyPerson.setWorkUnit(singleDTO.getWorkUnit());
		applyPerson.setTaxRegisterNo(singleDTO.getOrganCode1());
		applyPerson.setOrganCode(singleDTO.getOrganCode2());
		applyPerson.setBusinessLicenseCode(singleDTO.getOrganCode3());
		applyPerson.setSocietyCreditCode(singleDTO.getOrganCode4());
		applyPerson.setMobile(singleDTO.getMobileNo());
		applyPerson.setResidencePlace(singleDTO.getResidencePlace());
		applyPerson.setCreatorId(SystemConstants.SYS_OPERATOR);
		applyPerson.setCreateDate(DateUtil.getCurrentDate());
		applyPerson.setRcState(ENUM_RC_STATE.EFFECTIVE.getCode());
		return applyPerson;
	}

	/**
	 * 封装本系统的保单信息对象
	 * @param ReqAppPolicyDTO 核心DTO
	 * @return
	 */
	private TaxCont changeTaxCont(ReqAppPolicyDTO reqAppPolicyDTO) {
		TaxCont taxCont = new TaxCont();
		taxCont.setBizNo(reqAppPolicyDTO.getBizNo());
		taxCont.setProposalNo(reqAppPolicyDTO.getPolicyNo());
		taxCont.setContNo(reqAppPolicyDTO.getPolicyNo());
		taxCont.setContType(reqAppPolicyDTO.getPolicyType());
		taxCont.setContSource(reqAppPolicyDTO.getPolicySource());
		taxCont.setBelongedManageCode(reqAppPolicyDTO.getPolicyOrg());
		taxCont.setContArea(reqAppPolicyDTO.getPolicyArea());
		taxCont.setSaleChnl(reqAppPolicyDTO.getSalesChannel());
		taxCont.setSaleArea(reqAppPolicyDTO.getSalesArea());
		taxCont.setAppDate(DateUtil.parseDate(reqAppPolicyDTO.getAcceptDate()));
		taxCont.setConfirmDate(DateUtil.parseDate(reqAppPolicyDTO.getAcceptDate()));
		taxCont.setValiDate(DateUtil.parseDate(reqAppPolicyDTO.getEffectiveDate()));
		taxCont.setExpireDate(DateUtil.parseDate(reqAppPolicyDTO.getExpireDate()));
		taxCont.setContState(reqAppPolicyDTO.getPolicyStatus());
		taxCont.setOutCompanyCode(reqAppPolicyDTO.getOriginalOrganCode());
		taxCont.setOutContNo(reqAppPolicyDTO.getOriginalPolicyNo());
		taxCont.setSourceCode(ENUM_SENDSERVICE_CODE.CORE.code());
		taxCont.setAppType(ENUM_POLICY_TYPE.SINGLE_POLICY_HOLDER.code());
		taxCont.setRcState(ENUM_RC_STATE.EFFECTIVE.getCode());
		taxCont.setCreateDate(DateUtil.getCurrentDate());
		taxCont.setCreatorId(SystemConstants.SYS_OPERATOR);
		taxCont.setModifierId(SystemConstants.SYS_OPERATOR);
		taxCont.setModifyDate(DateUtil.getCurrentDate());
		return taxCont;
	}

	/**
	 * 责任信息
	 * @param Liability
	 * @param riskId
	 * @return
	 */
	private TaxContPolicyDuty changePolicyDuty(ReqAppLiabilityDTO liability, Integer riskId) {
		TaxContPolicyDuty duty = new TaxContPolicyDuty();
		duty.setPolId(riskId);
		duty.setDutyAmnt(liability.getLiabilitySa());
		duty.setDutyCode(liability.getLiabilityCode());
		duty.setDutyState(liability.getLiabilityStatus());
		duty.setCreatorId(SystemConstants.SYS_OPERATOR);
		duty.setCreateDate(DateUtil.getCurrentDate());
		duty.setModifierId(SystemConstants.SYS_OPERATOR);
		duty.setModifyDate(DateUtil.getCurrentDate());
		duty.setRcState(ENUM_RC_STATE.EFFECTIVE.getCode());
		return duty;
	}

	/**
	 * 核保信息
	 * @param underwriting
	 * @param riskId
	 * @return
	 */
	public TaxContPolicyUwinfo changeUwinfo(ReqAppUnderwritingDTO underwriting, Integer riskId) {
		TaxContPolicyUwinfo uwinfo = new TaxContPolicyUwinfo();
		uwinfo.setPolId(riskId);
		uwinfo.setUwDesipriton(underwriting.getUnderwritingDes());
		uwinfo.setUwResult(underwriting.getUnderwritingDecision());
		uwinfo.setUwTime(DateUtil.parseDate(underwriting.getUnderwritingDate()));
		uwinfo.setCreatorId(SystemConstants.SYS_OPERATOR);
		uwinfo.setCreateDate(DateUtil.getCurrentDate());
		uwinfo.setModifierId(SystemConstants.SYS_OPERATOR);
		uwinfo.setModifyDate(DateUtil.getCurrentDate());
		uwinfo.setRcState(ENUM_RC_STATE.EFFECTIVE.getCode());
		return uwinfo;
	}

	/**
	 * 缴费信息
	 * @param premium
	 * @param policyId
	 * @return
	 */
	public TaxContPayment changePayment(ReqAppPremiumDTO premium, Integer policyId) {
		TaxContPayment payment = new TaxContPayment();
		payment.setContId(policyId);
		payment.setEndPayDate(DateUtil.parseDate(premium.getPayToDate()));
		payment.setPayIntv(premium.getPaymentFrequency());
		payment.setPayNo(premium.getFeeId());
		payment.setPayState(premium.getFeeStatus());
		payment.setPrem(premium.getPremiumAmount());
		payment.setRcState(ENUM_RC_STATE.EFFECTIVE.getCode());
		payment.setSpayDate(DateUtil.parseDate(premium.getPayDueDate()));
		payment.setStartPayDate(DateUtil.parseDate(premium.getPayFromDate()));
		payment.setCreatorId(SystemConstants.SYS_OPERATOR);
		payment.setCreateDate(DateUtil.getCurrentDate());
		payment.setModifierId(SystemConstants.SYS_OPERATOR);
		payment.setModifyDate(DateUtil.getCurrentDate());
		payment.setApayDate(DateUtil.parseDate(premium.getConfirmDate()));
		return payment;
	}

	/**
	 * 封装中保信DTOList
	 * @param appAcceptBody
	 * @return
	 */
	private List<AppPolicyDTO> createDto(List<ReqAppPolicyDTO> appAcceptBody) {
		List<AppPolicyDTO> list = new ArrayList<AppPolicyDTO>();
		AppPolicyDTO appPolicyDTO = new AppPolicyDTO();
		for (ReqAppPolicyDTO reqAppPolicyDTO : appAcceptBody) {
			appPolicyDTO = this.createAppAcceptMore(reqAppPolicyDTO);
			list.add(appPolicyDTO);
		}
		return list;
	}

	/**
	 * 将核心DTO转换为中保信DTO集合
	 * @param reqAppPolicyDTO
	 *            核心信息DTO
	 * @return
	 */
	private AppPolicyDTO createAppAcceptMore(ReqAppPolicyDTO reqAppPolicyDTO) {
		AppPolicyDTO appPolicyDTO = new AppPolicyDTO();
		ReflectionUtil.copyProperties(reqAppPolicyDTO, appPolicyDTO);
		// 保单状态转码
		appPolicyDTO.setPolicyStatus(transCodeService.transCode(ENUUM_CODE_MAPPING.STATE.code(),reqAppPolicyDTO.getPolicyStatus()));
		// 个单
		AppSinglePolicyHolderDTO singlePolicyHolder = new AppSinglePolicyHolderDTO();
		if (reqAppPolicyDTO.getSinglePolicyHolder() != null) {
			ReflectionUtil.copyProperties(reqAppPolicyDTO.getSinglePolicyHolder(),singlePolicyHolder);
			// 性别和证件类别转码
			singlePolicyHolder.setGender(transCodeService.transCode(ENUUM_CODE_MAPPING.GENDER.code(),singlePolicyHolder.getGender()));
			singlePolicyHolder.setCertiType(transCodeService.transCode(ENUUM_CODE_MAPPING.CARDTYPE.code(),singlePolicyHolder.getCertiType()));
			appPolicyDTO.setSinglePolicyHolder(singlePolicyHolder);
		}
		// 团单
		if (reqAppPolicyDTO.getGroupPolicyHolder() != null) {
			AppGroupPolicyHolderDTO groupPolicyHolder = new AppGroupPolicyHolderDTO();
			ReqAppGroupPolicyHolderDTO reqAppGroupPolicyHolder = reqAppPolicyDTO.getGroupPolicyHolder();
			ReflectionUtil.copyProperties(reqAppGroupPolicyHolder, groupPolicyHolder);
			appPolicyDTO.setGroupPolicyHolder(groupPolicyHolder);
		}
		// 被保人
		List<AppInsuredDTO> insuredList = new ArrayList<AppInsuredDTO>();
		// 循环被保人
		if (this.checkList(reqAppPolicyDTO.getInsuredList())) {
			for (ReqAppInsuredDTO reqApp : reqAppPolicyDTO.getInsuredList()) {
				AppInsuredDTO appInsuredDTO = new AppInsuredDTO();
				// 缴费
				AppPremiumDTO appPremiumDTO = new AppPremiumDTO();
				ReflectionUtil.copyProperties(reqApp, appInsuredDTO);
				// 被保人性别 证件类别 职业代码转码
				appInsuredDTO.setGender(transCodeService.transCode(ENUUM_CODE_MAPPING.GENDER.code(), reqApp.getGender()));
				appInsuredDTO.setCertiType(transCodeService.transCode(ENUUM_CODE_MAPPING.CARDTYPE.code(),reqApp.getCertiType()));
				appInsuredDTO.setJobCode(transCodeService.transCode(ENUUM_CODE_MAPPING.JOBCODE.code(),reqApp.getJobCode()));
				ReqAppPremiumDTO premium = reqApp.getPremium();
				ReflectionUtil.copyProperties(premium, appPremiumDTO);
				// 缴费频率
				appPremiumDTO.setPaymentFrequency(transCodeService.transCode(ENUUM_CODE_MAPPING.PAYMENTFREQUENCY.code(), reqApp.getPremium().getPaymentFrequency()));
				appInsuredDTO.setPremium(appPremiumDTO);
				// 受益人
				List<AppBeneficiaryDTO> appBeneList = null;
				if (this.checkList(reqApp.getBeneficiaryList())) {
					appBeneList = new ArrayList<AppBeneficiaryDTO>();
					// 循环受益人
					for (ReqAppBeneficiaryDTO reqbene : reqApp.getBeneficiaryList()) {
						AppBeneficiaryDTO appBene = new AppBeneficiaryDTO();
						ReflectionUtil.copyProperties(reqbene, appBene);
						appBene.setPriority(reqbene.getPriority());
						appBene.setProportion(reqbene.getProportion());
						// 证件类别转码
						appBene.setCertiType(transCodeService.transCode(ENUUM_CODE_MAPPING.CARDTYPE.code(),reqbene.getCertiType()));
						// 受益人性别 转码
						appBene.setGender(transCodeService.transCode(ENUUM_CODE_MAPPING.GENDER.code(),reqbene.getGender()));
						appBeneList.add(appBene);
					}
				}
				// 险种
				List<AppCoverageDTO> appCoverageList = new ArrayList<AppCoverageDTO>();
				if (this.checkList(reqApp.getCoverageList())) {
					// 循环险种
					for (ReqAppCoverageDTO reqCover : reqApp.getCoverageList()) {
						AppCoverageDTO appCoverageDTO = new AppCoverageDTO();
						ReflectionUtil.copyProperties(reqCover, appCoverageDTO);
						// 主附险标志,险种状态转码
						appCoverageDTO.setCoverageType(transCodeService.transCode(ENUUM_CODE_MAPPING.MAINFLAG.code(),reqCover.getCoverageType()));
						appCoverageDTO.setCoverageStatus(transCodeService.transCode(ENUUM_CODE_MAPPING.STATE.code(),reqCover.getCoverageStatus()));
						// 核保
						AppUnderwritingDTO appUnderwritingDTO = new AppUnderwritingDTO();
						ReqAppUnderwritingDTO reqAppUnderwriting = reqCover.getUnderwriting();
						ReflectionUtil.copyProperties(reqAppUnderwriting, appUnderwritingDTO);
						appCoverageDTO.setUnderwriting(appUnderwritingDTO);
						// 责任信息
						List<AppLiabilityDTO> appLiabilityList = new ArrayList<AppLiabilityDTO>();
						if (this.checkList(reqCover.getLiabilityList())) {
							// 循环责任信息
							for (ReqAppLiabilityDTO reqLiability : reqCover.getLiabilityList()) {
								AppLiabilityDTO appLiabilityDTO = new AppLiabilityDTO();
								ReflectionUtil.copyProperties(reqLiability, appLiabilityDTO);
								appLiabilityDTO.setLiabilitySa(reqLiability.getLiabilitySa());
								// 责任状态转码
								appLiabilityDTO.setLiabilityStatus(transCodeService.transCode(ENUUM_CODE_MAPPING.LIABILITYSTATUS.code(),reqLiability.getLiabilityStatus()));
								appLiabilityList.add(appLiabilityDTO);
							}
						}
						appCoverageDTO.setLiabilityList(appLiabilityList);
						appCoverageList.add(appCoverageDTO);
					}
				}
				appInsuredDTO.setCoverageList(appCoverageList);
				appInsuredDTO.setBeneficiaryList(appBeneList);
				insuredList.add(appInsuredDTO);
			}
		}
		appPolicyDTO.setInsuredList(insuredList);
		return appPolicyDTO;
	}

	/**
	 * 判断list是否为空
	 * 
	 * @param list
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	private boolean checkList(List list) {
		return list != null && list.size() > 0;
	}

	/**
	 * 承保异常任务
	 */
	@SuppressWarnings("unchecked")
	@Override
	public TaxFaultTask applicantExceptionJob(String reqJSON, String portCode, Integer faultTaskId) {
		logger.info("进入承保异常任务服务");
		ThirdSendResponseDTO thirdSendResponse = new ThirdSendResponseDTO();// 响应核心的报文内容
		TaxFaultTask faultTask = taxFaultTaskMapper.selectByPrimaryKey(faultTaskId);
		String port = null;
		try {
			List<ReqBusinessDetailDTO> reqBusinessDetailList = new ArrayList<ReqBusinessDetailDTO>();
			ReqBusinessDTO businessDTO = commonCodeService.initReqBusinessDTO();
			List<ReqAppPolicyDTO> appAcceptBody = new ArrayList<ReqAppPolicyDTO>();
			ParamHeadDTO paramHead = new ParamHeadDTO();
			CoreRequestHead coreRequestHead = new CoreRequestHead();
			//1. 解析请求报文
			//单笔请求
			if (ENUM_HX_SERVICE_PORT_CODE.APPLICANT_ONE.code().equals(portCode)) {
				port = ENUM_HX_SERVICE_PORT_CODE.APPLICANT_ONE.desc();
				RepAppAcceptOneBody reqObject = JSONObject.parseObject(reqJSON,RepAppAcceptOneBody.class);
				ReqAppPolicyDTO apppolicyDTO = (ReqAppPolicyDTO) reqObject.getBody();
				appAcceptBody.add(apppolicyDTO);
				coreRequestHead = reqObject.getRequestHead();
			} else if (ENUM_HX_SERVICE_PORT_CODE.APPLICANT_MORE.code().equals(portCode)) {
				port = ENUM_HX_SERVICE_PORT_CODE.APPLICANT_MORE.desc();
				ReqAppAcceptMoreBody reqObject = JSONObject.parseObject(reqJSON, ReqAppAcceptMoreBody.class);
				appAcceptBody = (List<ReqAppPolicyDTO>) reqObject.getBody();
				coreRequestHead = reqObject.getRequestHead();
			} else {
				throw new BusinessDataErrException("请求接口编码有误! 错误接口编码为：" + portCode);
			}
			logger.info(port + "（核心请求）JSON 体数据内容：" + reqJSON);
			// 2. 封装头部信息
			paramHead.setPortCode(portCode);
			paramHead.setAreaCode(coreRequestHead.getAreaCode());
			paramHead.setRecordNum(coreRequestHead.getRecordNum());
			paramHead.setSerialNo(coreRequestHead.getSerialNo());
			ThirdSendDTO thirdSendDTO = new ThirdSendDTO();
			EbaoServerPortDTO ebaoServerPort = null;
			EBBody EBbody = new EBBody();

			Holder<ResponseHeader> responseHeaderHolder = new Holder<ResponseHeader>();
			Holder<ResponseBody> responseBodyHolder = new Holder<ResponseBody>();
			// 服务接口编码
			// 预约码处理方式
			if (ENUM_DISPOSE_TYPE.APPOINTMENT.code().equals(faultTask.getDisposeType())) {
				// 3. 封装请求中保信数据
				paramHead.setRecordNum("1"); //异步请求接口请求记录数为1
				BookSequenceDTO bookSequence = new BookSequenceDTO();
				bookSequence.setBookingSequenceNo(faultTask.getRemark());
				thirdSendDTO = commonCodeService.createThirdSend(ENUM_EBAO_SERVICE_PORT_CODE.GET_APPACCEPT_DISPOSE_RESULT.code(), paramHead, bookSequence);
				ebaoServerPort = commonCodeService.queryEBaoServerInfoByPortCode(ENUM_EBAO_SERVICE_PORT_CODE.ASYN_RESULT_QUERY.code());
				logger.info("预约码 - 承保上传（请求中保信）JSON 数据内容(预约码类型)："+ JSONObject.toJSONString(thirdSendDTO));
				String portUrl = ebaoServerPort.getPortUrl();
				URL wsdlLocation = new URL(portUrl);
				AsynResultQueryService_Service service = new AsynResultQueryService_Service(wsdlLocation);
				AsynResultQueryService servicePort = service.getAsynResultQueryServicePort();
				BindingProvider bp = (BindingProvider) servicePort;
				bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, portUrl);
				servicePort.asynResultQuery(thirdSendDTO.getHead(), thirdSendDTO.getBody(),responseHeaderHolder, responseBodyHolder);
			} else if (ENUM_DISPOSE_TYPE.ASYNC.code().equals(faultTask.getDisposeType())|| ENUM_DISPOSE_TYPE.ERROR.code().equals(faultTask.getDisposeType())) {
				List<AppPolicyDTO> appAcceptMoresList = this.createDto(appAcceptBody);
				EBbody.setPolicyList(appAcceptMoresList);
				thirdSendDTO = commonCodeService.createThirdSend(ENUM_EBAO_SERVICE_PORT_CODE.APPACCEPT_UPLOAD.code(),paramHead, EBbody);
				ebaoServerPort = commonCodeService.queryEBaoServerInfoByPortCode(ENUM_EBAO_SERVICE_PORT_CODE.APPACCEPT_UPLOAD.code());
				logger.info("异常任务 - 承保上传（请求中保信）JSON 数据内容(错误或异常类型)："+ JSONObject.toJSONString(thirdSendDTO));
				String portUrl = ebaoServerPort.getPortUrl();
				URL wsdlLocation = new URL(portUrl);
				PolicyInforceService_Service service = new PolicyInforceService_Service(wsdlLocation);
				PolicyInforceService servicePort = service.getPolicyInforceServicePort();
				BindingProvider bp = (BindingProvider) servicePort;
				bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, portUrl);
				servicePort.inforce(thirdSendDTO.getHead(), thirdSendDTO.getBody(),responseHeaderHolder, responseBodyHolder);
			} else {
				throw new BusinessDataErrException("异常类型有误! 错误异常类型为："+ ENUM_DISPOSE_TYPE.getEnumValueByKey(faultTask.getDisposeType()));
			}
			logger.info(port + "（请求中保信）JSON 数据内容："+ JSONObject.toJSONString(thirdSendDTO));
			
			ResponseHeader responseHeader = responseHeaderHolder.value;
			ResponseBody responseBody = responseBodyHolder.value;
			logger.info("异常任务 -" + port + "（中保信响应）JSON 数据内容："+ responseBody.getJsonString());
			ResponseJSON responseJSON = new ResponseJSON();
			responseJSON.setResponseBody(responseBody);
			responseJSON.setResponseHeader(responseHeader);
			// 如果是异步类型需要记录日志
			if (ENUM_DISPOSE_TYPE.ASYNC.code().equals(faultTask.getDisposeType())) {
				SendLogDTO sendLog = new SendLogDTO();
				sendLog.setSerialNo(paramHead.getSerialNo());
				sendLog.setPortCode(ENUM_EBAO_SERVICE_PORT_CODE.APPACCEPT_UPLOAD.code());
				sendLog.setRequestContent(JSONObject.toJSONString(thirdSendDTO));
				sendLog.setResponseContent(JSONObject.toJSONString(responseJSON));
				sendLog.setTargetCode(ENUM_SENDSERVICE_CODE.EBAO.code());
				sendLog.setState(ENUM_BZ_RESPONSE_RESULT.SUCCESS.code());
				sendLog.setDescription(ENUM_BZ_RESPONSE_RESULT.SUCCESS.description());
				commonCodeService.addLogSend(sendLog);
			}
			// 3.封装返回核心dto;
			String messageBody = ENUM_BZ_RESPONSE_RESULT.FAIL.description();
			if (ENUM_RESULT_CODE.SUCCESS.code().equals(responseHeader.getResultCode())
					|| ENUM_RESULT_CODE.INPUT_LOCALITY_SUCCESS.code().equals(responseHeader.getResultCode())) {
				thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.SUCCESS.code());
				thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.SUCCESS.description());
				// 解析中保信返回Dto
				AppAcceptResultBody resultlist = JSONObject.parseObject(responseBody.getJsonString(),AppAcceptResultBody.class);
				List<AppAcceptPolicyResultDTO> policyList = resultlist.getPolicyList();
				// 持久化
				addNewPolicy(appAcceptBody, policyList);
			}else if(ENUM_RESULT_CODE.REQ_AWAIT.code().equals(responseHeader.getResultCode())){
				thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.EXCEPTION.code());
				thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.EXCEPTION.description());
			}else{
				thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.FAIL.code());
				List list = responseHeader.getResultMessage().getMessage();
				if(list != null && list.size() > 0){
					StringBuffer sbStr = new StringBuffer(); 
					for(String mess : responseHeader.getResultMessage().getMessage()){
						sbStr.append(mess).append("|");
					}
					String message = messageBody = sbStr.substring(0, sbStr.length()-1).toString();
					thirdSendResponse.setResultDesc(message);
				}else{
					thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.FAIL.description());
				}
			}
			boolean isRegisterFaulTask = false;
			if (!StringUtil.isEmpty(responseBody.getJsonString())) {
				AppAcceptResultBody resultBody = JSONObject.parseObject(responseBody.getJsonString(),AppAcceptResultBody.class);
				if (null != resultBody.getPolicyList()) {
					// 成功记录数
					Integer successNum = 0;
					// 失败记录数
					Integer failNum = 0;
					// 返回核心Dto body
					StringBuffer sb = new StringBuffer();
					// 返回多条记录
					List<ResultApplicantDTO> bodylist = new ArrayList<ResultApplicantDTO>();
					// 保单list
					List<AppAcceptPolicyResultDTO> policyList = resultBody.getPolicyList();
					// 循环核心dto
					for (ReqAppPolicyDTO accept : appAcceptBody) {
						// 循环返回结果
						for (AppAcceptPolicyResultDTO r : policyList) {
							// 判断保单号
							if (r.getPolicyNo().equals(accept.getPolicyNo())) {
								List<ResultClient> clientList = new ArrayList<ResultClient>();
								ResultApplicantDTO body = new ResultApplicantDTO();
								body.setBizNo(accept.getBizNo());
								body.setPolicyNo(r.getPolicyNo());
								for (AppAcceptClientResultDTO c : r.getClientList()) {
									ResultClient client = new ResultClient();
									HXResultCodeDTO result = new HXResultCodeDTO();
									client.setTaxCode(c.getTaxCode());
									client.setSequenceNo(c.getSequenceNo());
									result.setResultCode(c.getResult().getResultCode());
									List<String> mes = c.getResult().getResultMessage();
									String message = "";
									if (mes != null) {
										for (String m : mes) {
											sb.append(m).append("|");
										}
										message = sb.substring(0,sb.length() - 1).toString();
										result.setResultMessage(message);
									}
									// 成功记录计数
									if (ENUM_RESULT_CODE.SUCCESS.code().equals(c.getResult().getResultCode())) {
										successNum += 1;
									} else {
										// 失败记录计数
										failNum += 1;
										ReqBusinessDetailDTO reqBusinessDetailDTO = commonCodeService.initReqBusinessDetailDTO(paramHead);
										reqBusinessDetailDTO.setResultCode(ENUM_BUSINESS_RESULR.FAIL.code());
										reqBusinessDetailDTO.setResultMessage(message);
										reqBusinessDetailList.add(reqBusinessDetailDTO);
									}
									client.setResult(result);
									clientList.add(client);
								}
								body.setClientList(clientList);
								bodylist.add(body);
							}
						}
					}
					// 返回核心对象
					if (ENUM_HX_SERVICE_PORT_CODE.APPLICANT_ONE.code().equals(portCode)) {
						thirdSendResponse.setResJson(bodylist.get(0));
					} else if (ENUM_HX_SERVICE_PORT_CODE.APPLICANT_MORE.code().equals(portCode)) {
						thirdSendResponse.setResJson(bodylist);
					}
					// 登记请求记录
					businessDTO.setReqSuccessNum(successNum);
					businessDTO.setReqFailNum(failNum);
					isRegisterFaulTask = true;
				}else{
					BookSequenceDTO bookSequence = JSONObject.parseObject(responseBody.getJsonString(),BookSequenceDTO.class);
					// 插入异常任务表
					faultTask.setRemark(bookSequence.getBookingSequenceNo());
					faultTask.setDisposeType(ENUM_DISPOSE_TYPE.APPOINTMENT.code());
					thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.EXCEPTION.code());
					thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.EXCEPTION.description());
				}
			} else {
				thirdSendResponse.setResJson(messageBody);
				businessDTO.setReqFailNum(responseHeader.getRecordNum());
				for (int i = 0; i < responseHeader.getRecordNum(); i++) {
					ReqBusinessDetailDTO reqBusinessDetailDTO = commonCodeService.initReqBusinessDetailDTO(paramHead);
					reqBusinessDetailDTO.setResultCode(ENUM_BUSINESS_RESULR.FAIL.code());
					reqBusinessDetailDTO.setResultMessage(thirdSendResponse.getResultDesc());
					reqBusinessDetailList.add(reqBusinessDetailDTO);
				}
			}
			if (isRegisterFaulTask) {
				// 添加失败交易记录
				commonCodeService.addReqBusinessDetail(reqBusinessDetailList);
				// 添加请求交易记录数
				businessDTO.setRequetNum(responseHeader.getRecordNum());
				commonCodeService.addReqBusinessCollate(businessDTO);
				faultTask.setDisposeResult(ENUM_BZ_RESPONSE_RESULT.SUCCESS.code());
			}else{
				faultTask.setDisposeResult(ENUM_BZ_RESPONSE_RESULT.FAIL.code());
			}
		} catch (Exception e) {
			e.printStackTrace();
			thirdSendResponse.setResJson(e.getMessage());
			thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.FAIL.code());
			thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.FAIL.description());
			logger.error("异常任务-" + port + "后置处理失败：" + e.getMessage());
			faultTask.setDisposeResult(ENUM_BZ_RESPONSE_RESULT.FAIL.code());
			if(ENUM_DISPOSE_TYPE.APPOINTMENT.code().equals(faultTask.getDisposeType())){
				faultTask.setDisposeType(ENUM_DISPOSE_TYPE.APPOINTMENT.code());
			}else{
				faultTask.setDisposeType(ENUM_DISPOSE_TYPE.ERROR.code());
			}
		} finally{
			faultTask.setSuccessMessage(JSONObject.toJSONString(thirdSendResponse));
			faultTask.setDisposeDate(DateUtil.getCurrentDate());
			taxFaultTaskMapper.updateByPrimaryKeySelective(faultTask);
		}
		logger.error(port + "异常任务处理结束!");
		return faultTask;
	}

	@Override
	public ThirdSendResponseDTO policyReversalExceptionJob(String reqJSON, String portCode, TaxFaultTask faultTask) {
		logger.info("进入承保撤销申请上传异常任务服务");
		ThirdSendResponseDTO thirdSendResponse = new ThirdSendResponseDTO();
		List<ReqBusinessDetailDTO> reqBusinessDetailList = new ArrayList<ReqBusinessDetailDTO>();
		try {
			ReqBusinessDTO businessDTO = commonCodeService.initReqBusinessDTO();
			ParamHeadDTO paramHeadDTO = new ParamHeadDTO();
			CoreRequestHead coreRequestHead = new CoreRequestHead();
			// 1. 解析请求报文ReqPolicyReversalDTO
			ReqPolicyReversalDTO reqObject = JSONObject.parseObject(reqJSON,ReqPolicyReversalDTO.class);
			ReqPolicyCancelDTO reqPolicyCancelDTO = (ReqPolicyCancelDTO) reqObject.getBody();
			coreRequestHead = reqObject.getRequestHead();
			// 将请求dto转换为中保信理赔请求dto
			PolicyReversalInfoDTO reversalInfo = this.createReversalInfoDTO(reqPolicyCancelDTO);
			PolicyReversalDTO reversalDTO = new PolicyReversalDTO();
			reversalDTO.setPolicyCancel(reversalInfo);
			// 2. 封装头部信息
			paramHeadDTO.setPortCode(portCode);
			paramHeadDTO.setAreaCode(coreRequestHead.getAreaCode());
			paramHeadDTO.setRecordNum(coreRequestHead.getRecordNum());
			paramHeadDTO.setSerialNo(coreRequestHead.getSerialNo());
			ThirdSendDTO thirdSendDTO = commonCodeService.createThirdSend(ENUM_EBAO_SERVICE_PORT_CODE.POLICY_REVERSAL.code(),paramHeadDTO, reversalDTO);
			logger.info("异常任务 -承保撤销（请求中保信）JSON 数据内容：" + JSONObject.toJSONString(thirdSendDTO));
			Holder<ResponseHeader> responseHeaderHolder = new Holder<ResponseHeader>();
			Holder<ResponseBody> responseBodyHolder = new Holder<ResponseBody>();
			// 3.调用中保信接口服务,获得返回结果 存储调用中保信日志表
			EbaoServerPortDTO ebaoServerPort = commonCodeService.queryEBaoServerInfoByPortCode(ENUM_EBAO_SERVICE_PORT_CODE.POLICY_REVERSAL.code());
			String portUrl = ebaoServerPort.getPortUrl();
			URL wsdlLocation = new URL(portUrl);
			PolicyReversalService_Service service = new PolicyReversalService_Service(wsdlLocation);
			PolicyReversalService servicePort = service.getPolicyReversalServicePort();
			BindingProvider bp = (BindingProvider) servicePort;
			bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, portUrl);
			servicePort.reversal(thirdSendDTO.getHead(),thirdSendDTO.getBody(), responseHeaderHolder,responseBodyHolder);
			ResponseHeader responseHeader = responseHeaderHolder.value;
			ResponseBody responseBody = responseBodyHolder.value;
			logger.info("异常任务 -承保撤销上传（中保信响应）JSON 数据内容："+ responseBody.getJsonString());

			String messageBody = ENUM_BZ_RESPONSE_RESULT.FAIL.description();
			if (ENUM_RESULT_CODE.SUCCESS.code().equals(responseHeader.getResultCode())
					|| ENUM_RESULT_CODE.INPUT_LOCALITY_SUCCESS.code().equals(responseHeader.getResultCode())) {
				thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.SUCCESS.code());
				thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.SUCCESS.description());
				this.updatePolicyState(reversalInfo.getPolicyNo());
			}else{
				thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.FAIL.code());
				List list = responseHeader.getResultMessage().getMessage();
				if(list != null && list.size() > 0){
					StringBuffer sbStr = new StringBuffer(); 
					for(String mess : responseHeader.getResultMessage().getMessage()){
						sbStr.append(mess).append("|");
					}
					String message = sbStr.substring(0, sbStr.length()-1).toString();
					thirdSendResponse.setResultDesc(message);
				}else{
					thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.FAIL.description());
				}
				faultTask.setDisposeResult(ENUM_BZ_RESPONSE_RESULT.FAIL.code());
			}
			if (!StringUtil.isEmpty(responseBody.getJsonString())) {
				PolicyReversalResultDTO reversalResultDTO = JSONObject.parseObject(responseBody.getJsonString(),PolicyReversalResultDTO.class);
				EBResultCodeDTO eBResultCode = reversalResultDTO.getPolicy().getResult();
				String message = "";
				ResultApplicantReversalDTO reversDTO = new ResultApplicantReversalDTO();
				HXResultCodeDTO resultDTO = new HXResultCodeDTO();
				if (null != eBResultCode.getResultMessage()) {
					StringBuffer sbStr = new StringBuffer();
					for (String mess : eBResultCode.getResultMessage()) {
						sbStr.append(mess).append("|");
					}
					message = sbStr.substring(0, sbStr.length() - 1).toString();
				}
				resultDTO.setResultMessage(message);
				resultDTO.setResultCode(eBResultCode.getResultCode());
				reversDTO.setResult(resultDTO);
				thirdSendResponse.setResJson(reversDTO);
				if (ENUM_RESULT_CODE.SUCCESS.code().equals(eBResultCode.getResultCode())) {
					businessDTO.setReqSuccessNum(businessDTO.getReqSuccessNum() + 1);
				} else {
					businessDTO.setReqFailNum(businessDTO.getReqFailNum() + 1);
					ReqBusinessDetailDTO reqBusinessDetailDTO = commonCodeService.initReqBusinessDetailDTO(paramHeadDTO);
					reqBusinessDetailDTO.setResultCode(ENUM_BUSINESS_RESULR.FAIL.code());
					reqBusinessDetailDTO.setResultMessage(message);
					reqBusinessDetailList.add(reqBusinessDetailDTO);
				}
			} else {
				thirdSendResponse.setResJson(messageBody);
				businessDTO.setReqFailNum(responseHeader.getRecordNum());
				ReqBusinessDetailDTO reqBusinessDetailDTO = commonCodeService.initReqBusinessDetailDTO(paramHeadDTO);
				reqBusinessDetailDTO.setResultCode(ENUM_BUSINESS_RESULR.FAIL.code());
				reqBusinessDetailDTO.setResultMessage(thirdSendResponse.getResultDesc());
				reqBusinessDetailList.add(reqBusinessDetailDTO);
			}
			// 添加失败交易记录
			commonCodeService.addReqBusinessDetail(reqBusinessDetailList);
			businessDTO.setRequetNum(responseHeader.getRecordNum());
			commonCodeService.addReqBusinessCollate(businessDTO);
			faultTask.setDisposeResult(ENUM_BZ_RESPONSE_RESULT.SUCCESS.code());
		} catch (Exception e) {
			e.printStackTrace();
			thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.FAIL.code());
			thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.FAIL.description());
			logger.error("承保撤销异常任务服务方法处理发生异常! 异常信息为：" + e.getMessage());
			faultTask.setDisposeType(ENUM_DISPOSE_TYPE.ERROR.code());
			faultTask.setDisposeResult(ENUM_BZ_RESPONSE_RESULT.FAIL.code());
		} finally{
			faultTask.setSuccessMessage(JSONObject.toJSONString(thirdSendResponse));
			faultTask.setDisposeDate(DateUtil.getCurrentDate());
			taxFaultTaskMapper.updateByPrimaryKeySelective(faultTask);
		}
		logger.info("承保撤销异常任务服务方法处理结束!");
		return thirdSendResponse;
	}
}
